using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.MaterialFile;
using System.Text;

namespace RBAC.Read.Api.Application.Handler.ERP.MaterialFile
{
    /// <summary>
    /// 获取物料分类列表处理程序 - 支持树状图展示和模糊查询
    /// </summary>
    public class GetMaterTypeListHandler : IRequestHandler<GetMaterTypeListCommand, APIResult<List<GetMaterTypeListDto>>>
    {
        private readonly IBaseRepository<MaterType> materTypeRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetMaterTypeListHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materTypeRepository">物料分类仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetMaterTypeListHandler(
            IBaseRepository<MaterType> materTypeRepository,
            IMapper mapper,
            ILogger<GetMaterTypeListHandler> logger)
        {
            this.materTypeRepository = materTypeRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取物料分类列表请求
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>物料分类树状列表数据</returns>
        public async Task<APIResult<List<GetMaterTypeListDto>>> Handle(GetMaterTypeListCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<GetMaterTypeListDto>>();

            try
            {
                logger.LogInformation("开始获取物料分类列表，分类名称: {TypeName}, 状态: {Status}, 父级ID: {ParentId}",
                    request.TypeName, request.Status, request.ParentId);

                // 构建查询条件
                var whereClause = new StringBuilder("IsDeleted = false");
                var parameters = new Dictionary<string, object>();

                // 按分类名称模糊查询
                if (!string.IsNullOrEmpty(request.TypeName))
                {
                    whereClause.Append(" AND TypeName LIKE @TypeName");
                    parameters.Add("TypeName", $"%{request.TypeName}%");
                }

                // 按状态筛选
                if (request.Status.HasValue)
                {
                    whereClause.Append(" AND Status = @Status");
                    parameters.Add("Status", request.Status.Value);
                }

                // 按父级ID筛选
                if (request.ParentId.HasValue)
                {
                    whereClause.Append(" AND ParentId = @ParentId");
                    parameters.Add("ParentId", request.ParentId.Value);
                }

                // 添加排序条件 - 使用CreateTime降序排序，确保最新创建的在前面
                string orderByClause = "CreateTime DESC";

                // 查询所有分类数据
                var sql = $"SELECT * FROM MaterType WHERE {whereClause} ORDER BY {orderByClause}";
                var materTypes = materTypeRepository.Query<MaterType>(sql, parameters).ToList();

                // 构建树状结构
                var treeData = BuildTreeStructure(materTypes);

                result.Code = APIEnums.Success;
                result.Data = treeData;
                result.Msg = "获取物料分类列表成功";

                logger.LogInformation("获取物料分类列表成功，共 {Count} 个分类", materTypes.Count);
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Error;
                result.Msg = "获取物料分类列表失败";
                logger.LogError(ex, "获取物料分类列表失败: {Message}", ex.Message);
            }

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 构建树状结构
        /// </summary>
        /// <param name="materTypes">物料分类列表</param>
        /// <returns>树状结构数据</returns>
        private List<GetMaterTypeListDto> BuildTreeStructure(List<MaterType> materTypes)
        {
            var materTypeDict = materTypes.ToDictionary(x => x.Id);
            var treeData = new List<GetMaterTypeListDto>();

            foreach (var materType in materTypes)
            {
                if (materType.ParentId == null || !materTypeDict.ContainsKey(materType.ParentId.Value))
                {
                    // 顶级分类
                    var dto = mapper.Map<GetMaterTypeListDto>(materType);
                    dto.Children = GetChildren(materTypes, materType.Id);
                    treeData.Add(dto);
                }
            }

            return treeData;
        }

        /// <summary>
        /// 递归获取子分类
        /// </summary>
        /// <param name="materTypes">所有分类</param>
        /// <param name="parentId">父级ID</param>
        /// <returns>子分类列表</returns>
        private List<GetMaterTypeListDto> GetChildren(List<MaterType> materTypes, long parentId)
        {
            var children = new List<GetMaterTypeListDto>();
            var childMaterTypes = materTypes.Where(x => x.ParentId == parentId).ToList();

            foreach (var child in childMaterTypes)
            {
                var dto = mapper.Map<GetMaterTypeListDto>(child);
                dto.Children = GetChildren(materTypes, child.Id);
                children.Add(dto);
            }

            return children;
        }
    }
}